const CameraUtils = {
	mediaRecorder: null,
	mediaStream: null,
	stopRecordCallback: null,
	chunks: [],
	MediaUtils: {
		/**
		 * 获取用户媒体设备(处理兼容的问题)
		 * @param callback {Function} - 处理回调
		 */
		getUserMedia(callback) {

			let constraints = {
				audio: true,
				video: true
			};
			if (navigator.mediaDevices && navigator.mediaDevices.getUserMedia) {
				navigator.mediaDevices.getUserMedia(constraints).then(function(stream) {
					callback(false, stream);
				}).catch(function(err) {
					callback(err);
				});
			} else if (navigator.getUserMedia) {
				navigator.getUserMedia = navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia ||
					navigator.msGetUserMedia || window.getUserMedia;
				navigator.getUserMedia(constraints, function(stream) {
					callback(false, stream);
					console.log("+++++++++++++++++++++");
				}, function(err) {
					callback(err);
				});
			} else {
				callback(new Error('Not support userMedia'));
			}
		},

		/**
		 * 关闭媒体流
		 * @param stream {MediaStream} - 需要关闭的流
		 */
		closeStream(stream) {
			if (typeof stream.stop === 'function') {
				stream.stop();
			} else {
				let trackList = [stream.getAudioTracks(), stream.getVideoTracks()];
				for (let i = 0; i < trackList.length; i++) {
					let tracks = trackList[i];
					if (tracks && tracks.length > 0) {
						for (let j = 0; j < tracks.length; j++) {
							let track = tracks[j];
							if (typeof track.stop === 'function') {
								track.stop();
							}
						}
					}
				}
			}
		}
	},
	/** 初始化相机
	 * @param {HTMLMediaElement} videoDom
	 */
	init(videoDom) {
		this.MediaUtils.getUserMedia((err, stream) => {
			if (err) {
				throw err;
			} else {
				this.mediaRecorder = new MediaRecorder(stream);
				this.initMediaRecorderEvent();
				videoDom.srcObject = stream;
				this.mediaStream = stream;
				videoDom.onloadedmetadata = function() {
					this.play();
				};
			}
		});
	},
	/**
	 * 开始录像
	 * @param {Number} time
	 * @param {Function} callback
	 */
	start(time, callback) {
		"inactive" === this.mediaRecorder.state && this.mediaRecorder.start();
		setTimeout(() => {
			// 结束
			this.stopRecord(callback);
		}, time);
	},

	initMediaRecorderEvent() {
		this.mediaRecorder.addEventListener("dataavailable", e => {
			this.chunks.push(e.data);
		});

		this.mediaRecorder.onstop = () => {
			if(this.chunks.length>1){
				let recorderFile = new Blob(this.chunks, {
					type: "video/webm"
				});
				this.chunks = [];
				if (recorderFile &&null != this.stopRecordCallback) {
					this.toBase64(recorderFile);
				}
			}
		};
	},

	stopRecord(callback) {
		this.stopRecordCallback = callback;
		// 终止录制
		if (this.mediaRecorder) {
			"recording" === this.mediaRecorder.state && this.mediaRecorder.stop();
		}
		if (this.mediaStream) {
			this.MediaUtils.closeStream(this.mediaStream);
		}
	},

	/**
	 * 文件转缓存数组
	 */
	toBase64(data) {
		let fileReader = new FileReader();
		fileReader.readAsDataURL(data);
		fileReader.addEventListener("loadend", () => {
			let video_base64 = fileReader.result.split(",")[1];
			this.stopRecordCallback(video_base64);
			clearTimeout(this.stopVideo);
		});
	}
}
